import PropTypes from 'prop-types'
import React, { createRef, memo, useEffect, useRef, useState } from 'react'
import ScrollViewWrapper from './style'
import IconArrowLeft from '@/assets/svg/icon-arrow-left'
import IconArrowRight from '@/assets/svg/icon-arrow-right'

const ScrollView = memo((props) => {
  // 获取conter的节点信息
  const scrollViewRef = createRef()
  // 定义右边按钮初始值
  const [showRight, setShowRight] = useState(false)
  const [showLeft, setShowLeft] = useState(false)
  const [posIndex, setPosIndex] = useState(0)

  // 定义一个ref，用来保存数据不被刷新
  let totalDistanceRef = useRef()

  // DOM更新完成后加载
  useEffect(() => {
    // 加载完成后获取tab的可以滚动长度
    const scrollWidth = scrollViewRef.current.scrollWidth
    // 获取由内容撑起来的长度
    const clientWidth = scrollViewRef.current.clientWidth
    // 计算可滚动 - 内容长度 剩余的长度
    const totalDistance = scrollWidth - clientWidth
    // 剩余的长度记录给totalDistanceRef
    totalDistanceRef.current = totalDistance
    setShowRight(totalDistance > 0)
  // 每次children变化时再重新加载
  },[props.children])
  
  // 左边点击事件
  function contorClickHandle(isRight){
    const newIndex = isRight?posIndex + 1 : posIndex - 1
    // 找到scrollViewRef下面的子节点
    const newEl = scrollViewRef.current.children[newIndex]
    // 计算偏移一个item是多少px
    const newEloffSet = newEl.offsetLeft
    // 给scrollViewRef节点设置样式
    scrollViewRef.current.style.transform = `translate(-${newEloffSet}px)`
    // 记录偏移的是第几个item
    setPosIndex(newIndex)
    // newEloffSet 会递增，总长度少于递增长度，按钮隐藏
    setShowRight(totalDistanceRef.current > newEloffSet)
    setShowLeft(newEloffSet > 0)
  }
  
  return (
    <ScrollViewWrapper>
      {showLeft && 
        (<div className='control left' onClick={e => contorClickHandle(false)}>
          <IconArrowLeft onClick={e => contorClickHandle(false)}/>
        </div>
      )}
      {showRight && 
        (<div className='control right' onClick={e => contorClickHandle(true)}>
          <IconArrowRight/>
          </div>
        )}
      <div className='scroll'>
        <div className='scroll-content' ref={scrollViewRef}>
          {props.children}
        </div>
      </div>
    </ScrollViewWrapper>
  )
})

ScrollView.propTypes = {

}

export default ScrollView